<style lang="less">
    @import "index.less";
    .map {
        width: 100%;
        height: 280px;
    }
</style>

<template>
    <div class="device-edit-view">
        <Form ref="editForm" :model="fields" :rules="rules">
            <Row :gutter="16">
                <Col span="14">
                <Card>
                    <p slot="title">基础信息</p>
                    <Row>
                        <Col>
                        <FormItem label="设备编号" prop="device_sn">
                            <Input v-model="fields.device_sn" disabled></Input>
                        </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col>
                        <FormItem label="设备名称" prop="name">
                            <Input v-model="fields.name"></Input>
                        </FormItem>
                        </Col>
                    </Row>
                    <Row :gutter="6" class="ladder-price-card">
                        <Col span="12">
                        <FormItem label="1级定价：">
                            <Input readonly type="number" :number="true" maxlength="5" v-model="fields.ladder_price.one.min">
                            </Input>
                            <Input type="number" @on-change="fields.ladder_price.two.min=fields.ladder_price.one.max" :number="true" maxlength="5" v-model="fields.ladder_price.one.max">
                            <span slot="prepend">到</span>
                            <span slot="append">分钟</span>
                            </Input>
                            <Input type="number" :number="true" maxlength="5" v-model="fields.ladder_price.one.price">
                            <span slot="append" style="color:red;">元</span>
                            </Input>
                        </FormItem>
                        </Col>
                        <Col span="12">
                        <FormItem label="2级定价：">
                            <Input readonly type="number" :number="true" maxlength="5" v-model="fields.ladder_price.two.min">
                            </Input>
                            <Input type="number" @on-change="fields.ladder_price.three.min=fields.ladder_price.two.max" :number="true" maxlength="5" v-model="fields.ladder_price.two.max">
                            <span slot="prepend">到</span>
                            <span slot="append">分钟</span>
                            </Input>
                            <Input type="number" :number="true" maxlength="5" v-model="fields.ladder_price.two.price">
                            <span slot="append" style="color:red;">元</span>
                            </Input>
                        </FormItem>
                        </Col>
                        <Col span="12">
                        <FormItem label="3级定价：">
                            <Input readonly type="number" :number="true" maxlength="5" v-model="fields.ladder_price.three.min">
                            </Input>
                            <Input type="number" @on-change="fields.ladder_price.four.min=fields.ladder_price.three.max" :number="true" maxlength="5" v-model="fields.ladder_price.three.max">
                            <span slot="prepend">到</span>
                            <span slot="append">分钟</span>
                            </Input>
                            <Input type="number" :number="true" maxlength="5" v-model="fields.ladder_price.three.price">
                            <span slot="append" style="color:red;">元</span>
                            </Input>
                        </FormItem>
                        </Col>
                        <Col span="12" class="four-ladder-price">
                        <FormItem label="4级定价：">
                            <Input type="number" :number="true" maxlength="5" v-model="fields.ladder_price.four.price">
                            <span slot="prepend">{{ fields.ladder_price.four.min }}分钟后</span>
                            <span slot="append" style="color:red;">元</span>
                            </Input>
                        </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col>
                        <FormItem label="备注" prop="remark">
                            <Input v-model="fields.remark"></Input>
                        </FormItem>
                        </Col>
                    </Row>
                    <Row style="padding:10px; text-align: center;">
                        <Button :loading="editBtnLoading" type="success" @click="handleSubmit">修改</Button>
                        <Button @click="backPage">返回</Button>
                    </Row>
                </Card>
                </Col>
                <Col span="10">
                <Card>
                    <p slot="title">地理位置信息</p>
                    <Row>
                        <FormItem label="省市区">
                            <Cascader :data="regions" v-model="regionSelected" trigger="hover" @on-change="handleRegionChange"></Cascader>
                        </FormItem>
                    </Row>
                    <Row>
                        <FormItem label="详细地址(点击地图选择经纬度)" prop="address">
                            <Input type="text" v-model="fields.address" @on-blur="handleAddressInputBlur"></Input>
                        </FormItem>
                    </Row>
                    <Row>
                        <Row :gutter="16">
                            <Col span="8"><span style="font-weight: bold; color: red;">经度：{{ fields.coordinate.lng }}</span></Col>
                            <Col span="8"><span style="font-weight: bold; color: red;">纬度：{{ fields.coordinate.lat }}</span></Col>
                        </Row>
                        <baidu-map :zoom="zoom" :center="center"  @click="handleClickMap" class="map">
                            <bm-marker :position="fields.coordinate"
                                       :dragging="true"
                                       :auto-viewport='true'
                                       animation="BMAP_ANIMATION_BOUNCE" @dragend='dragend'></bm-marker>
                            <bm-local-search :keyword.sync="fullAddress" :panel="false" :auto-viewport="true"></bm-local-search>
                        </baidu-map>
                    </Row>
                </Card>
                </Col>
            </Row>
        </Form>
    </div>
</template>

<script>
    import util from '@/libs/util';
    export default {
        data () {
            return {
                zoom: 15,
                center: '',

                regions: [],
                regionLoading: false,
                regionsText: '',
                regionSelected: [],
                fullAddress: '',

                editBtnLoading: false,

                fields: {
                    id: '',
                    device_sn: '',
                    name: '',
                    province_code: '',
                    city_code: '',
                    district_code: '',
                    address: '',
                    remark: '',
                    coordinate: { lng: 0, lat: 0 },
                    ladder_price: {
                        one: {
                            min: 0,
                            max: 0,
                            price: 1
                        },
                        two: {
                            min: 0,
                            max: 0,
                            price: 2
                        },
                        three: {
                            min: 0,
                            max: 0,
                            price: 5
                        },
                        four: {
                            min: 0,
                            max: 999999,
                            price: 10
                        }
                    }
                },

                rules: {
                    name: [
                        { required: true, message: '请输入设备名称', trigger: 'blur'},
                        { type: 'string', min: 2, max: 30, message: '名称格式必须是2~30个字符' }
                    ],
                    address: [
                        { required: true, message: '请输入详细地址', trigger: 'blur'},
                        { type: 'string', min: 3, message: '最少3个字' }
                    ],
                }
            }
        },

        watch: {
            'fields.address': function (value) {
                this.fullAddress = this.regionsText + value;
            }
        },

        created () {
            this.getRegions();
            this.getDevice();
        },

        methods: {
            backPage () {
                this.$store.commit('removeTag', this.$route.name);
                this.$router.push({
                    name: 'system-device-list'
                });
            },

            handleSubmit () {
                this.$refs.editForm.validate((valid) => {
                    if (valid && this.validatorLadderPrice() && this.validatorRegion()) {
                        this.edit(this.fields);
                    } else {
                        this.$Message.error('表单数据验证失败');
                    }
                });
            },

            edit (data) {
                this.editBtnLoading = true;
                util.api().put(`/admin/api/devices/${this.fields.id}`, data).then((resp) => {
                    console.log(resp.data.data);
                    if (resp.data.status == true) {
                        this.$Notice.success({ title: resp.data.message});
                        this.backPage();
                    } else {
                        this.$Notice.error({ title: resp.data.message});
                    }
                    this.editBtnLoading = false;
                }).catch((e) => {
                    util.handleApiException(e, this, '修改设备失败');
                    this.editBtnLoading = false;
                })
            },

            validatorLadderPrice() {
                const ladder_price = this.fields.ladder_price;
                if (ladder_price.one.min != 0) {
                    this.$Notice.error({ title: '设备定价阶梯必须从0分钟开始计算'});
                    return false;
                } else if (ladder_price.one.min >= ladder_price.one.max) {
                    this.$Notice.error({ title: '1级定价阶梯时间范围填写错误，开始时间必须小于结束时间'});
                    return false;
                } else if (ladder_price.two.min != ladder_price.one.max) {
                    this.$Notice.error({ title: '2级定价阶梯必须从1级定价结束时间开始'});
                    return false;
                } else if (ladder_price.two.min >= ladder_price.two.max) {
                    this.$Notice.error({ title: '2级定价阶梯时间范围填写错误，开始时间必须小于结束时间'});
                    return false;
                } else if (ladder_price.three.min != ladder_price.two.max) {
                    this.$Notice.error({ title: '3级定价阶梯必须从2级定价结束时间开始'});
                    return false;
                } else if (ladder_price.three.min >= ladder_price.three.max) {
                    this.$Notice.error({ title: '3级定价阶梯时间范围填写错误，开始时间必须小于结束时间'});
                    return false;
                } else if (ladder_price.four.min != ladder_price.three.max) {
                    this.$Notice.error({ title: '4级定价阶梯必须从3级定价结束时间开始'});
                    return false;
                }

                return true;
            },

            validatorRegion () {
                if (this.regionSelected.length == 0) {
                    this.$Notice.error({ title: '地理位置信息不完整', desc: '请选择省市区'});
                    return false;
                } else if (this.fields.coordinate.lat === 0 && this.fields.coordinate.lng === 0) {
                    this.$Notice.error({ title: '地理位置信息不完整', desc: '请点击地图设置经纬度坐标点'});
                    return false;
                }

                return true;
            },

            handleClickMap(e) {
                this.fields.coordinate = e.point;
            },

            handleAddressInputBlur () {
                this.fields.coordinate = { lng: 0, lat: 0 };
            },

            handleRegionChange (value, data) {
                console.log(value, data);
                let regionsText = '';
                for (let i in data) {
                    regionsText += data[i].label;
                }

                this.fields.province_code = value[0];
                this.fields.city_code = value[1];
                this.fields.district_code = value[2];

                this.regionsText = regionsText;
                this.fullAddress = regionsText + this.fields.address;
            },

            getDevice () {
                const id = this.$route.query.id;
                if (!id) {
                    this.$Notice.error({ title: '获取设备信息失败' });
                    this.backPage();
                } else {
                    util.api().get(`/admin/api/devices/${id}`).then((resp) => {
                        if (resp.data.status == true) {
                            const fields = {
                                id: resp.data.data.id,
                                device_sn: resp.data.data.device_sn,
                                name: resp.data.data.name,
                                province_code: resp.data.data.province_code,
                                city_code: resp.data.data.city_code,
                                district_code: resp.data.data.district_code,
                                address: resp.data.data.address,
                                remark: resp.data.data.remark,
                                coordinate: resp.data.data.coordinate,
                                ladder_price: resp.data.data.ladder_price
                            };

                            this.fields = fields;
                            this.center = fields.coordinate;
                            this.regionSelected = [fields.province_code, fields.city_code, fields.district_code];
                        } else {
                            this.$Notice.error({ title: '获取设备信息失败' });
                            this.backPage();
                        }
                    }).catch((e) => {
                        util.handleApiException(e, this, '获取设备信息失败');
                        this.backPage();
                    })
                }
            },

            getRegions () {
                this.regionLoading = true;
                util.ajax.get('/api/regions/format').then((resp) => {
                    const formatTree = (arr, level = 1) => {
                        let regions = [];
                        for (let i in arr) {
                            let node = {};
                            node.value = arr[i].code;
                            node.label = arr[i].name;
                            node.level = level;
                            node.disabled = arr[i].disabled;
                            if (arr[i].hasOwnProperty('children')) {
                                node.children = formatTree(arr[i].children, level++);
                            }

                            regions.push(node);
                        }
                        return regions;
                    };

                    this.regions = formatTree(resp.data.data);
                    this.regionLoading = false;
                }).catch((e) => {
                    this.regionLoading = false;
                    util.handleApiException(e, this, '获取省市区数据失败');
                })
            },

        }
    }
</script>
